﻿using System.Collections;
using System.Collections.Generic;
using Unity.Collections;
using Unity.Jobs;
using UnityEngine;

public class JobSystem2 : MonoBehaviour {

	// Use this for initialization
	void Start () {
        NativeArray<float> a = new NativeArray<float>(2, Allocator.TempJob);

        NativeArray<float> b = new NativeArray<float>(2, Allocator.TempJob);

        NativeArray<float> result = new NativeArray<float>(2, Allocator.TempJob);

        a[0] = 1.1f;
        b[0] = 2.2f;
        a[1] = 3.3f;
        b[1] = 4.4f;

        Job2 jobData = new Job2();
        jobData.a = a;
        jobData.b = b;
        jobData.result = result;

        // Schedule the job with one Execute per index in the results array and only 1 item per processing batch
        //使用result数组中的每个索引执行一次Execute并且每次处理过程只处理一个项目
        JobHandle handle = jobData.Schedule(result.Length, 1);

        // Wait for the job to complete
        handle.Complete();

        for (int i = 0; i < result.Length; i++) {
            Debug.Log("result "+i+": "+result[i]);
        }

        // Free the memory allocated by the arrays
        //释放内存
        a.Dispose();
        b.Dispose();
        result.Dispose();
    }
}

public struct Job2 : IJobParallelFor {

    public NativeArray<float> a;
    public NativeArray<float> b;

    public NativeArray<float> result;

    public void Execute(int index) {
        result[index] = a[index] + b[index];
    }
}